package sample.stackbak.number;

import sample.stackbak.symbol.StackInft;

/**
 * @author 陈镇雨
 */
public class LinkStack implements StackInft {
    /**
     * 栈顶指针
     */
    Stacknode top;

    /**
     * 空参构造
     */
    public LinkStack() {
        //建立一个空栈
        top = null;
    }

    /**
     * 入栈
     *
     * @param obj
     */
    @Override
    public void push(Object obj) {
        Stacknode s = null;
        //生成新结点
        s = new Stacknode();
        //新结点的数据域为 obj
        s.data = Double.parseDouble(obj.toString());
        //再链入新结点，使S的下一指向为新结点
        s.next = top;
        //修改栈顶指针
        top = s;
    }

    /**
     * 出栈
     *
     * @return
     */
    @Override
    public Object pop() {
        Stacknode p = null;
        double x;
        if (top == null) {
            return null;
        } else {
            x = top.data;
            p = top;
            top = p.next;
            p = null;
            return x;
        }
    }

    /**
     * 栈深
     *
     * @return
     */
    @Override
    public int size() {
        int i = 0;
        Stacknode p = top;
        while (p != null) {
            i++;
            p = p.next;
        }
        return i;
    }

    /**
     * 清空栈
     */
    @Override
    public void clear() {
        top = null;
    }

    /**
     * 判断空栈
     */
    @Override
    public void isEmpty() {
        if (top == null) {
            System.out.println("该栈为空");
        } else {
            System.out.println("该栈不为空");
        }

    }

    /**
     * 栈顶元素
     *
     * @return
     */
    @Override
    public Object top() {
        if (top != null) {
            return top.data;
        } else {
            return null;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        int i = 0;
        if (top != null) {
            Stacknode p = top;
            while (p != null) {
                sb.append(String.valueOf(p.data));
                i++;
                if (p.next != null) {
                    sb.append(", ");
                }
                p = p.next;
            }
        }
        sb.append("] , 栈深为= ").append(String.valueOf(i));
        return sb.toString();
    }
}
